package com.meilingcloud.research.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.meilingcloud.common.annotation.Log;
import com.meilingcloud.common.core.controller.BaseController;
import com.meilingcloud.common.core.domain.AjaxResult;
import com.meilingcloud.common.core.page.TableDataInfo;
import com.meilingcloud.common.enums.BusinessType;
import com.meilingcloud.common.enums.TopicTaskState;
import com.meilingcloud.common.utils.SecurityUtils;
import com.meilingcloud.research.domain.RwsTask;
import com.meilingcloud.research.domain.RwsTopic;
import com.meilingcloud.research.domain.RwsTopicUser;
import com.meilingcloud.research.service.IRwsTaskService;
import com.meilingcloud.research.service.IRwsTopicService;
import com.meilingcloud.research.service.IRwsTopicUserService;
import com.meilingcloud.system.service.ISysCustomFormService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课题 Controller
 *
 * @author chenl
 * @date 2021-03-23
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/research/topic")
public class RwsTopicController extends BaseController {

    private final IRwsTopicService iRwsTopicService;
    private final IRwsTopicUserService iRwsTopicUserService;
    private final IRwsTaskService iRwsTaskService;

    private final ISysCustomFormService iSysCustomFormService;

    /**
     * 根据成员查询课题 列表
     */
    @PreAuthorize("@ss.hasPermi('research:topic:list')")
    @GetMapping("/list")
    public TableDataInfo list(RwsTopic rwsTopic) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        List<RwsTopicUser> topicUsers = iRwsTopicUserService.list(new LambdaQueryWrapper<RwsTopicUser>()
                .eq(RwsTopicUser::getUserId, userId));
        if (CollectionUtil.isNotEmpty(topicUsers)) {
            List<Long> topicIds = topicUsers.stream().map(RwsTopicUser::getTopicId).collect(Collectors.toList());
            startPage();
            List<RwsTopic> list = iRwsTopicService.queryList(rwsTopic, topicIds);
            List<RwsTopic> collect = list.stream().map(item -> {
                List<RwsTask> rwsTasks = iRwsTaskService.list(new LambdaQueryWrapper<RwsTask>().eq(RwsTask::getTopicId, item.getTopicId()));
                int doneCount = (int) rwsTasks.stream().filter(i -> TopicTaskState.DONE.getCode().equals(i.getTaskState())).count();
                int undoneCount = (int) rwsTasks.stream().filter(i -> TopicTaskState.UNDONE.getCode().equals(i.getTaskState())).count();
                item.setDoneTaskCount(doneCount);
                item.setUnDoneTaskCount(undoneCount);
                return item;
            }).collect(Collectors.toList());
            return getDataTable(collect);
        } else {
            return getDataTable(new ArrayList<>());
        }
    }

    /**
     * 查询当前用户所在成员的所有课题 不分页
     */
    @GetMapping("/listAll")
    public AjaxResult listAll() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        List<RwsTopicUser> topicUsers = iRwsTopicUserService.list(new LambdaQueryWrapper<RwsTopicUser>()
                .eq(RwsTopicUser::getUserId, userId));
        List<RwsTopic> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(topicUsers)) {
            List<Long> topicIds = topicUsers.stream().map(RwsTopicUser::getTopicId).collect(Collectors.toList());
            list = iRwsTopicService.list(new LambdaQueryWrapper<RwsTopic>().in(RwsTopic::getTopicId, topicIds));
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询当前用户所在成员的所有课题和表单
     */
    @GetMapping("/listAllAndFrom")
    public AjaxResult listAllAndFrom() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        List<RwsTopicUser> topicUsers = iRwsTopicUserService.list(new LambdaQueryWrapper<RwsTopicUser>()
                .eq(RwsTopicUser::getUserId, userId));
        List<RwsTopic> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(topicUsers)) {
            List<Long> topicIds = topicUsers.stream().map(RwsTopicUser::getTopicId).collect(Collectors.toList());
            list = iRwsTopicService.list(new LambdaQueryWrapper<RwsTopic>().in(RwsTopic::getTopicId, topicIds));
        }
        for (RwsTopic rwsTopic : list) {
            Map<String, List<String>> stringListMap = iSysCustomFormService.formDataShow(rwsTopic.getFormKey());
            rwsTopic.setFormMap(stringListMap);
        }

        return AjaxResult.success(list);
    }

    /**
     * 获取课题 详细信息
     */
    @PreAuthorize("@ss.hasPermi('research:topic:query')")
    @GetMapping(value = "/{topicId}")
    public AjaxResult getInfo(@PathVariable("topicId") Long topicId) {
        return AjaxResult.success(iRwsTopicService.getById(topicId));
    }

    /**
     * 新增课题
     */
    @PreAuthorize("@ss.hasPermi('research:topic:add')")
    @Log(title = "课题列表 ", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody RwsTopic rwsTopic) {
        rwsTopic.setCreateBy(SecurityUtils.getUsername());
        return toAjax(iRwsTopicService.saveTopic(rwsTopic));
    }

    /**
     * 修改课题
     */
    @PreAuthorize("@ss.hasPermi('research:topic:edit')")
    @Log(title = "课题列表 ", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody RwsTopic rwsTopic) {
        rwsTopic.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(iRwsTopicService.updateTopic(rwsTopic));
    }

    /**
     * 删除课题
     */
    @PreAuthorize("@ss.hasPermi('research:topic:remove')")
    @Log(title = "课题列表 ", businessType = BusinessType.DELETE)
    @DeleteMapping("/{topicId}")
    public AjaxResult remove(@PathVariable("topicId") Long topicId) {
        return toAjax(iRwsTopicService.removeTopicById(topicId));
    }

    /**
     * 设置成员
     */
    @PostMapping("/addMembers")
    @Log(title = "课题列表 ", businessType = BusinessType.OTHER)
    public AjaxResult addMembers(@RequestBody List<RwsTopicUser> topicUsers) {
        return toAjax(iRwsTopicUserService.addMember(topicUsers));
    }

    /**
     * 获取成员
     */
    @GetMapping("/getMembers/{topicId}")
    public AjaxResult getMembers(@PathVariable("topicId") Long topicId) {
        return AjaxResult.success(iRwsTopicUserService.getMembers(topicId));
    }
}
